package org.jdcenter.rmi.impl;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class DelayedObject implements Delayed {
    private static final AtomicLong sequencer = new AtomicLong(0);
    private static final long NANO_ORIGIN = System.nanoTime();

    private final long now() {
        return System.nanoTime() - NANO_ORIGIN;
    }

    private final long sequenceNumber;
    private long time;

    public DelayedObject(long delay) {
        this.time = now() + TimeUnit.SECONDS.toNanos(delay);
        this.sequenceNumber = sequencer.getAndIncrement();
    }

    public long getDelay(TimeUnit unit) {
        return unit.convert(time - now(), TimeUnit.NANOSECONDS);
    }

    public int compareTo(Delayed other) {
        if (other == this) // compare zero ONLY if same object
            return 0;
        DelayedObject x = (DelayedObject) other;
        long diff = time - x.time;
        if (diff < 0)
            return -1;
        else if (diff > 0)
            return 1;
        else if (sequenceNumber < x.sequenceNumber)
            return -1;
        else
            return 1;
    }
}

